<?php
/** 
 * Copyright (c) 2014, Jiehun.com.cn Inc. All Rights Reserved
 * @author dengxiaolong@jiehun.com.cn
 * @date 2014-3-5
 * @version 1.0 
 * @brief 
 * 
 */

require_once dirname(__FILE__).'/FastcgiClient.php';
final class Fastcgi
{
	private $_params = array(
		'GATEWAY_INTERFACE' => 'FastCGI/1.0',
		'SERVER_SOFTWARE'   => 'php/fcgiclient',
		'SERVER_PROTOCOL'   => 'HTTP/1.1',
		'SERVER_NAME'       => 'hapn',
		'SERVER_ADDR'       => '127.0.0.1',
		'SERVER_PORT'       => '8000',
		'HTTP_USER_AGENT'	=> 'hapn/fcgiclient 1.0',
	);
	
	private $_server;
	private $_script;
	private $_client;
	
	function __construct($conf)
	{
		$this->_server = $conf['server'];
		if (!is_readable($conf['params']['SCRIPT_FILENAME'])) {
			throw new Exception('fastcgi.scriptIsNotReadable');
		} else {
			$conf['params']['SCRIPT_FILENAME'] = realpath($conf['params']['SCRIPT_FILENAME']);
		}
		if (!isset($conf['params']['DOCUMENT_URI'])) {
			$conf['params']['DOCUMENT_URI'] = $conf['params']['SCRIPT_FILENAME'];
		}
		if (!isset($conf['params']['SCRIPT_NAME'])) {
			$conf['params']['SCRIPT_NAME'] = basename($conf['params']['SCRIPT_FILENAME']);
		}
		foreach($conf['params'] as $key => $value) {
			$this->_params[$key] = $value;
		}
	}
	
	/**
	 * @return FastcgiClient
	 */
	private function _getClient()
	{
		if (!$this->_client) {
			$this->_client = new FastcgiClient($this->_server);
		}
		return $this->_client;
	}
	
	function get($url)
	{
		$params = array_merge($this->_params, array(
			'REQUEST_METHOD'    => 'GET',
			'CONTENT_TYPE'      => '',
			'CONTENT_LENGTH'    => 0,
		));
		$this->_initParams($params, $url);
		
		$client = $this->_getClient();
		return $client->request($params, false);
	}
	
	function post($url, $postData)
	{
		$params = array_merge($this->_params, array(
			'REQUEST_METHOD'    => 'POST',
			'CONTENT_TYPE'      => 'application/x-www-form-urlencoded',
		));
		$this->_initParams($params, $url);
		
		$postData = http_build_query($postData);
		$params['CONTENT_LENGTH'] = strlen($postData);
		
		$client = $this->_getClient();
		return $client->request($params, $postData);
	}
	
	private function _initParams(&$params, $url)
	{
		$info = parse_url($url);
		$params['HTTP_HOST'] = $info['host'];
		if (!isset($info['port'])) {
			$info['port'] = 80;
		}
		if (!isset($info['query'])) {
			$info['query'] = '';
		}
		$params['REQUEST_URI'] = $info['path'].($info['query'] ? '?'.$info['query'] : '');
		$params['SCRIPT_URL'] = $info['path'];
		$params['QUERY_STRING'] = $info['query'];
		
		$params['SERVER_PORT'] = $info['port'];
	}
}